import 'package:cotton_candy/components/input.dart';
import 'package:cotton_candy/notifier/theme_notifier.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ChatList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ChatListState();
  }
}

class _ChatListState extends State {
  final _controller = ScrollController();
  double _top = 0;
  bool _reloading = false;
  void _pointerUp(PointerUpEvent event) {
    if (_controller.offset <= 0) {
      double top = -_top - 50;
      if (top > 30) {
        setState(() {
          _reloading = true;
        });
        Future.delayed(Duration(milliseconds: 1000)).then((value) {
          setState(() {
            _reloading = false;
          });
        });
      }
    }
  }

  @override
  void initState() {
    _controller.addListener(() {
      // print('${_controller.position.maxScrollExtent}:${_controller.offset}');
      if (_controller.offset <= 0) {
        setState(() {
          _top = _controller.offset;
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double top = -_top - 50;
    String desc = '下拉可刷新';
    double iconOpacity = 1;
    if (top > 30) {
      top = 30;
      iconOpacity = 0;
      desc = '撒手刷新';
    }
    if (_reloading) {
      top = top + 20;
      if (top < 0) top = 0;
    }
    final Color primaryColor = context.watch<ThemeNotifier>().primaryColor;
    final Color gridentToColor = primaryColor.withAlpha(0);
    return Listener(
      onPointerUp: _pointerUp,
      onPointerDown: (_) {
        // 触摸收起软盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Stack(
        children: [
          ListView.builder(
            physics: BouncingScrollPhysics(),
            itemCount: 30,
            padding: EdgeInsets.fromLTRB(0, 10, 0, 600),
            controller: _controller,
            itemBuilder: (context, index) {
              if (index == 0) {
                return Container(
                  height: 40,
                  margin: EdgeInsets.fromLTRB(20, 20, 20, 10),
                  decoration: BoxDecoration(
                      color: Colors.white70,
                      borderRadius: BorderRadius.circular(20)),
                  child: Input(
                    placeholder: '搜索',
                    icon: Icons.search,
                    color: Color.fromARGB(200, 120, 120, 120),
                  ),
                );
              }

              return _ChatItem(
                avatarUrl:
                    'https://portrait.gitee.com/uploads/avatars/user/530/1591829_zvi_1578955391.png!avatar60',
                unreadCount: 0,
                name: 'nekv jang',
                timestamp: DateTime.now().millisecond,
                message: 'hallo werd!',
              );
            },
          ),
          Positioned(
            top: top,
            left: 0,
            right: 0,
            child: Visibility(
                visible: !_reloading,
                child: Column(
                  children: [
                    Opacity(
                      opacity: iconOpacity,
                      child: Icon(
                        Icons.arrow_downward_rounded,
                        color: Colors.white70,
                      ),
                    ),
                    Text(desc, style: TextStyle(color: Colors.white70)),
                  ],
                )),
          ),
          Positioned(
            top: -1,
            left: 0,
            right: 0,
            child: Container(
              height: 20,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                    primaryColor,
                    // Color.fromARGB(255, 37, 143, 159),
                    gridentToColor,
                  ])),
            ),
          ),
          Positioned(
            top: top,
            left: 0,
            right: 0,
            child: Visibility(
                visible: _reloading,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Theme(
                      data: ThemeData.dark(),
                      child: CupertinoActivityIndicator(
                        radius: 8,
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 4),
                      child: Text(
                        '正在刷新',
                        style: TextStyle(color: Colors.white70),
                      ),
                    )
                  ],
                )),
          ),
        ],
      ),
    );
  }
}

class _ChatItem extends StatefulWidget {
  final String avatarUrl;
  final String name;
  final String message;
  final int unreadCount;
  final int timestamp;
  _ChatItem(
      {@required this.avatarUrl,
      @required this.name,
      @required this.message,
      @required this.unreadCount,
      @required this.timestamp});
  @override
  State<StatefulWidget> createState() {
    return _ChatItemState();
  }
}

class _ChatItemState extends State<_ChatItem> {
  bool _isPressed = false;
  void handleTapDown(_) {
    setState(() {
      _isPressed = true;
    });
  }

  void handleTapUp(_) {
    setState(() {
      _isPressed = false;
    });
  }

  void handleTapCancel() {
    setState(() {
      _isPressed = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: handleTapDown,
      onTapUp: handleTapUp,
      onTapCancel: handleTapCancel,
      onTap: () {
        Navigator.pushNamed(context, '/chat');
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
        color: Color.fromARGB(_isPressed ? 10 : 0, 0, 0, 0),
        child: Row(
          children: [
            //头像
            ClipOval(
              child: Container(
                width: 46,
                height: 46,
                color: Color.fromARGB(180, 255, 255, 255),
                child: Image.network(widget.avatarUrl),
              ),
            ),
            Expanded(
              child: Container(
                padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
                margin: EdgeInsets.only(left: 15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        //昵称
                        Text(widget.name,
                            style: TextStyle(
                                fontSize: 14,
                                height: 1.5,
                                fontWeight: FontWeight.bold,
                                color: Colors.white70)),
                        //消息内容
                        Text(
                          widget.message,
                          style: TextStyle(
                              fontSize: 12, height: 1.5, color: Colors.white54),
                        ),
                      ],
                    ),
                    //未读消息数或时间
                    widget.unreadCount == 0
                        ? Text(
                            '刚刚',
                            style: TextStyle(
                                fontSize: 12,
                                height: 1.5,
                                color: Colors.white54),
                          )
                        : Container(
                            height: 20,
                            padding: EdgeInsets.fromLTRB(6, 2, 6, 0),
                            decoration: BoxDecoration(
                                color: Color.fromARGB(255, 200, 50, 50),
                                boxShadow: [
                                  BoxShadow(
                                      color: Colors.black12,
                                      offset: Offset(0, 1),
                                      blurRadius: 1)
                                ],
                                borderRadius: BorderRadius.circular(20)),
                            child: Center(
                              child: Text(
                                '99+',
                                style: TextStyle(
                                    height: 1,
                                    fontSize: 12,
                                    color: Colors.white),
                              ),
                            ),
                          ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
